package com.cong.security.service.impl;

import java.util.concurrent.TimeUnit;

import com.cong.security.core.code.sms.SmsCodeSender;
import com.cong.security.core.constant.CodeConstant;
import com.cong.security.core.properties.SecurityProperties;
import com.cong.security.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SmsCodeSenderImpl implements SmsCodeSender {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private AccountService accountService;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void send(String type, String mobile, String code) {
        boolean send = true;
        log.info("调用第三方平台发送短信验证码,发送成功send == true,否则send == false");
        if (send) {
            // 短信发送成功的情况下将发送短信写入缓存
            redisTemplate.opsForValue().set(type + ":" + mobile, code,
                    securityProperties.getCode().getSms().getExpireIn(), TimeUnit.SECONDS);
        }
    }

    @Override
    public String test(UsersConnectionRepository usersConnectionRepository, String type, String mobile, String code,
                       String deviceId) {
        // 从缓存中读取数据(任一存储逻辑都可以)
        String smsString = (String) redisTemplate.opsForValue().get(type + ":" + mobile);
        if (code.equals(smsString)) {
            // 绑定逻辑
            if (type.equals(CodeConstant.BIND)) {
                log.info("绑定操作,此时用户采用第三方账户(微信/QQ)登录,且该第三方账户未在本平台内注册");
            }
            // 不是绑定操作,默认是注册登录操作,调用接口查询用户信息(存在及成功,不存在即注册,返回成功)
            return accountService.smsLogin(mobile);
        } else {
            return "fail";
        }
    }
}
